package com.zhangtai.modules.service.impl.dimission;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zhangtai.exception.RException;
import com.zhangtai.modules.controller.admin.EmployessController;
import com.zhangtai.modules.dao.DimissionDao;
import com.zhangtai.modules.dao.EmployeeInfoDao;
//import com.zhangtai.modules.entity.DimissionAndEmployeeInfoEntity;
import com.zhangtai.modules.entity.employee.DimissionEntity;
import com.zhangtai.modules.entity.employee.EmployeeInfoEntity;
import com.zhangtai.modules.service.baseFromMssql.BaseMssqlServiceImpl;
import com.zhangtai.modules.service.dimission.DimissionService;
import com.zhangtai.modules.vo.DimissionEntityVo;
import com.zhangtai.utils.BeanUtilsMabach;
import com.zhangtai.utils.PageResult;
import com.zhangtai.utils.R;
import org.apache.commons.lang3.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

@RestController
public class DimissionServiceImpl extends ServiceImpl<DimissionDao, DimissionEntity> implements DimissionService {

	@Autowired
	private BaseMssqlServiceImpl baseMssqlServiceImpl;
	@Autowired
    private EmployeeInfoDao employeeInfoDao;
    @Autowired
    private BaseMssqlServiceImpl jobService;
    @Autowired
    private DimissionDao dimissionDao;
    @Autowired
    private EmployessController employessController;
	
    @Override
    public PageResult queryPage(@RequestParam(value = "hiredate", required = false) String hiredate,
								@RequestParam(value = "code", required = false) String code,
								@RequestParam(value = "name", required = false) String name,
								@RequestParam(value = "systemName", required = false) String systemName,
                                @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
                                @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {

    	//字符串转换成日期
    	java.util.Date date = null;
    	if(!StringUtils.isEmpty(hiredate)) {
    		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
       	 try {
       		   date = format.parse(hiredate);
       		   } catch (ParseException e) {
       		    e.printStackTrace();
       		   }
    	}
    	 
    	 //根据体系名称获取体系id
    	 List<Long> job_system_id_list = null;
    	 if(!StringUtils.isEmpty(systemName)) {
    		 job_system_id_list = baseMssqlServiceImpl.findSystemIdByName(systemName);
    		 
    	 }
        IPage<DimissionEntity> page = this.page(
                new Page<DimissionEntity>(pageNum,pageSize),
                new QueryWrapper<DimissionEntity>().like(!StringUtils.isEmpty(name),"name",name)
                        .eq("is_delete",0)
                        .eq(!StringUtils.isEmpty(code), "code",code)
                        .eq(!StringUtils.isEmpty(hiredate), "hiredate", date)
                        .in(!CollectionUtils.isEmpty(job_system_id_list),"job_system_id", job_system_id_list)
        );

        return new PageResult(page);
    }
    
    /**
     * 原生分页
     */
    @Override
	public PageResult<DimissionEntityVo> queryPageList(@RequestParam(value = "hiredate", required = false) Date hiredate,
								@RequestParam(value = "code", required = false) String code,
								@RequestParam(value = "name", required = false) String name,
								@RequestParam(value = "systemName", required = false) String systemName,
					            @RequestParam(value = "pageNum", defaultValue = "1") Integer pageNum,
					            @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize,
                                                @RequestParam(value = "orgIds") List<Long> orgIds){

    	//根据体系名称获取体系id
   	 List<Long> jobIds = null;
   	 if(!StringUtils.isEmpty(systemName)) {
   		jobIds = baseMssqlServiceImpl.findSystemIdByName(systemName);
   		 
   	 }
    	Page<DimissionEntityVo> page = new Page<DimissionEntityVo>(pageNum,pageSize);
    	List<DimissionEntityVo> list = dimissionDao.getDimissionList(hiredate, code, name, jobIds, page,orgIds);
    	page.setRecords(list);
    	return new PageResult(page);
	}
    
    //根据工号获取员工离职bpm表单
    @Override
	public R<DimissionEntityVo> employeeInfo(String userCode,String name) {
        //创建json
        //JSONObject json = new JSONObject();
    	DimissionEntityVo dimissionEntityVo = new DimissionEntityVo();
        
        //接收EmployeeInfo数据（包括本地mysql或bpm）
        EmployeeInfoEntity employeeInfo = new EmployeeInfoEntity();
        DimissionEntity list1 = new DimissionEntity();

        	//查询本地的主表
        	EmployeeInfoEntity list = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", userCode).eq("is_delete", 0));
            if(ObjectUtils.isEmpty(list)) {
            	//bpm存在返回实体，不存在返回null
            	employeeInfo = jobService.finEmpFromMssqlByCode(userCode);
                if(ObjectUtils.isEmpty(employeeInfo)) {
                	employeeInfo = null;
                }else {
                	//employeeInfo = employeeInfo;
                	//bpm存在数据，这时候就得判断是否是复职员工
                	//if(!employeeInfo.getEmployeestatus().equals("2")
                	//		|| !employeeInfo.getEmployeestatus().equals("9")) {
                	//}else {
                		dimissionEntityVo = BeanUtilsMabach.doToDto(employeeInfo, DimissionEntityVo.class);
                	//}
                	
                }
            }else {
            	employeeInfo = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("oid", list.getOid()).eq("is_delete", 0));
            	dimissionEntityVo = BeanUtilsMabach.doToDto(employeeInfo, DimissionEntityVo.class);
            
            	list1 = dimissionDao.selectOne(new QueryWrapper<DimissionEntity>().eq("oid", list.getOid()).eq("is_delete", 0));
            	if(list1 != null) {
            		
            		dimissionEntityVo = BeanUtilsMabach.doToDto(list1, DimissionEntityVo.class);
            	}
            }

        //主表人员信息
        //json.put("employeeInfo", employeeInfo);
        //json.put("dimission", list1);
        
        return R.ok(dimissionEntityVo);
	}
    
    //离职新增数据
    @Override
    @Transactional
	public R insetDimissionAndEmployeeInfo(DimissionEntity data, HttpServletRequest request) throws Exception {
    	
    	//人员基础表实体
    	EmployeeInfoEntity employeeInfoEntity = BeanUtilsMabach.doToDto(data, EmployeeInfoEntity.class);
    	//离职实体
    	DimissionEntity dimissionEntity = BeanUtilsMabach.doToDto(data, DimissionEntity.class);
    	if(!ObjectUtils.isEmpty(employeeInfoEntity)) {
    		EmployeeInfoEntity list = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", employeeInfoEntity.getCode()).eq("is_delete", 0));
    		if(!ObjectUtils.isEmpty(list)) {
    			//根据查到的人员数据更新对应数据
    			employeeInfoDao.updateById(employeeInfoEntity);
    		}else {
    			//否则插入一条数据
                employeeInfoEntity.setInsetDate(new Date());
				employeeInfoEntity.setEmployeeOid(Long.parseLong(employessController.getUserCode()));
    			employeeInfoDao.insert(employeeInfoEntity);
    		}
    	}else {
    		throw new RException("数据信息为空");
    	}
    	
    	//查询拿到新增或更新后的oid（员工ID）
    	EmployeeInfoEntity list1 = employeeInfoDao.selectOne(new QueryWrapper<EmployeeInfoEntity>().eq("code", employeeInfoEntity.getCode()).eq("is_delete", 0));
    	if(!ObjectUtils.isEmpty(list1)) {
    		//设置员工ID
    		dimissionEntity.setOid(list1.getOid());
    		//插入一条数据
    		dimissionDao.insert(dimissionEntity);
    		//附件url不为空
    		if(!ObjectUtils.isEmpty(data.getUrl_ids())) {
    			//附件url，插入img_url表
        		baseMssqlServiceImpl.urlIds(data.getUrl_ids(), list1.getOid());
    		}
    		
    	}else {
    		throw new RException("插入不能为空");
    	}
    	
    	return R.ok();
	}
    
    @Override
    public DimissionEntity getByIdE(Long id) {
            DimissionEntity one = this.getOne(new QueryWrapper<DimissionEntity>().eq("id", id).eq("is_delete", 0));

        return one;
    }

    @Override
    public R saveE(DimissionEntity entity) {
        boolean b = this.save(entity);
        if (!b){
            return R.error();
        }
        return R.ok();

    }

    @Override
    public R updateByIdE(DimissionEntity entity) {
        boolean b = this.updateById(entity);
        if (!b){
            return R.error();
        }
        return R.ok();
    }

    @Override
    public R removeOneById(Long id) {
            DimissionEntity entity = new DimissionEntity();
        entity.setId(id);
        entity.setIsDelete(1);
        boolean b = this.updateById(entity);
        if (!b){
            return R.error();
        }
        return R.ok();
    }

    @Override
    @Transactional
    public R removeByIdsE(List<Long> ids) {
        for (Long id : ids) {
            R r = removeOneById(id);
            if (!r.getFlag()){
                return r;
            }
        }
        return R.ok();
    }

}